package com.alphathink.deliveryassist.fragment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.AlphaThink.DeliveryAssist.R;
import com.alphathink.deliveryassist.AboutAlphaThink;
import com.alphathink.deliveryassist.ChangePwdActivity;
import com.alphathink.deliveryassist.LoginActivity;
import com.alphathink.deliveryassist.commonutils.L;
import com.alphathink.deliveryassist.http.NetOperater;
import com.alphathink.deliveryassist.message.templates.ModelActivity;
import com.alphathink.deliveryassist.util.ClearCache;
import com.alphathink.deliveryassist.util.SharePrefUtil;

/**
 * 
 * 我的信息 设置一些界面
 * 
 * @author click
 * 
 */
public class MyFragment extends Fragment {
	private static String TAG = null;

	private RelativeLayout mPasswd, mSmsTemp, mUpdate, mAbout;
	private Button mExit;

	private WidgetListener widgetListener = null;
	private View view = null;

	private SharedPreferences sharedPreferences = null;

	private NetOperater netOperater = null;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		view = inflater
				.inflate(R.layout.activity_my_fragment, container, false);
		initView();
		return view;
	}

	/**
	 * 初始化界面中view信息
	 * 
	 */
	private void initView() {
		TAG = getActivity().toString();
		// sharedPreferences = getActivity().getPreferences(
		// getActivity().MODE_PRIVATE);
		sharedPreferences = SharePrefUtil.getPref(getActivity()
				.getApplicationContext());
		widgetListener = new WidgetListener();
		netOperater = new NetOperater();

		mPasswd = (RelativeLayout) view.findViewById(R.id.id_my_passwd);
		mSmsTemp = (RelativeLayout) view.findViewById(R.id.id_my_smstemp);
		mUpdate = (RelativeLayout) view.findViewById(R.id.id_my_update);
		mAbout = (RelativeLayout) view.findViewById(R.id.id_my_about);

		mExit = (Button) view.findViewById(R.id.id_my_exit);

		mPasswd.setOnClickListener(widgetListener);
		mSmsTemp.setOnClickListener(widgetListener);
		mUpdate.setOnClickListener(widgetListener);
		mAbout.setOnClickListener(widgetListener);

		mExit.setOnClickListener(widgetListener);
	}

	/**
	 * 
	 * 控件监听事件处理
	 * 
	 * @author click
	 * 
	 */
	class WidgetListener implements OnClickListener {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.view.View.OnClickListener#onClick(android.view.View)
		 */
		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			switch (v.getId()) {
			case R.id.id_my_passwd:
				L.d(TAG, "修改密码");
				intent.setClass(getActivity(), ChangePwdActivity.class);
				startActivity(intent);
				break;
			case R.id.id_my_smstemp:
				L.d(TAG, "短信模板");
				intent.setClass(getActivity(), ModelActivity.class);
				startActivity(intent);
				break;
			case R.id.id_my_update:
				L.d(TAG, "软件升级");
				// 做出软件升级的效果
				String checkVersionUrl = sharedPreferences.getString(
						SharePrefUtil.CHECK_VERSION_URL,
						SharePrefUtil.CHECK_VERSION_URL);
				if ("".equals(checkVersionUrl)) {
					checkVersionUrl = "www.baidu.com";
				}
				CheckVersionAsyntask asyntask = new CheckVersionAsyntask(
						checkVersionUrl);
				asyntask.execute(checkVersionUrl);
				break;
			case R.id.id_my_about:
				L.d(TAG, "关于助手");
				intent.setClass(getActivity(), AboutAlphaThink.class);
				startActivity(intent);
				break;
			case R.id.id_my_exit:
				L.d(TAG, "退出登陆");
				ClearCache.cleanExternalCache(getActivity()
						.getApplicationContext());
				ClearCache.cleanInternalCache(getActivity()
						.getApplicationContext());
				Editor editor = sharedPreferences.edit();
				editor.clear();
				editor.commit();

				intent.setClass(getActivity(), LoginActivity.class);
				startActivity(intent);
				getActivity().finish();
				break;

			default:
				break;
			}

		}

	}

	/**
	 * 检查软件版本，与服务器进行交互 查询 版本信息
	 * 
	 * @ClassName: CheckVersionAsyntask
	 * @Description: TODO
	 * @param String
	 *            版本检测的url
	 * @author AT xpg
	 * @date 2015-4-2 下午8:46:47
	 * 
	 */
	class CheckVersionAsyntask extends AsyncTask<String, Integer, String> {
		private String url;
		ProgressDialog dialog = null;

		public CheckVersionAsyntask(String checkVersionUrl) {
			url = checkVersionUrl;

		}

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(getActivity());
			dialog.setMessage("请稍后。。。");
			dialog.setCancelable(true);
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String serverVersion = netOperater.CheckVersion(url);
			Log.d(TAG, "serverVersion--->" + serverVersion);
			return serverVersion;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
			String localVersion = sharedPreferences.getString(
					SharePrefUtil.LOCAL_VERSION, "");
			Log.d(TAG, "版本更新中本地版本号" + localVersion);
			if ("".equals(result)) {
				dialog.cancel();
				Toast.makeText(getActivity().getApplication(), "为接收到网络返回信息",
						Toast.LENGTH_SHORT).show();
				return;

			}
			if ("LOCAL_VERSION".equals(localVersion)) {
				localVersion = "1";
			}
			L.d(TAG, "本地版本信息" + localVersion);
			if (localVersion.equals(result)) {
				Toast.makeText(getActivity(), "当前版本已是最新版本", Toast.LENGTH_SHORT)
						.show();
			} else if (Integer.valueOf(result) > Integer.valueOf(localVersion)) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setMessage("有新版本,是否更新？")
						.setCancelable(false)
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {

										String updateUrl = sharedPreferences
												.getString(
														SharePrefUtil.UPDATE_VERSION_URL,
														SharePrefUtil.UPDATE_VERSION_URL);
										String tmp = "www.baidu.com";
										if ("".equals(updateUrl)) {
											updateUrl = tmp;
										}
										L.d(TAG, "更新时候的url" + updateUrl);
										UpdateVersionAsyntask asyntask = new UpdateVersionAsyntask(
												updateUrl);
										asyntask.execute();
									}
								})
						.setNegativeButton("否",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			}
			super.onPostExecute(result);
		}
	}

	/**
	 * 升级版本
	 * 
	 * @ClassName: UpdateVersionAsyntask
	 * @Description: TODO
	 * @author AT xpg
	 * @date 2015-4-2 下午11:17:27
	 * 
	 */
	class UpdateVersionAsyntask extends AsyncTask<String, Integer, String> {
		private String mUpdateURL = "";
		int hasDownload = 0;
		ProgressDialog dialog = null;

		/**
		 * 
		 * <p>
		 * Title:版本更新
		 * </p>
		 * <p>
		 * Description:
		 * </p>
		 * 
		 * @param updateVersion
		 *            版本更新的网址
		 * @author AT XPG
		 */
		public UpdateVersionAsyntask(String updateURL) {
			mUpdateURL = updateURL;

		}

		@SuppressLint("NewApi")
		@Override
		protected String doInBackground(String... params) {
			publishProgress(0);
			String update = "";

			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			InputStream inputStream = null;
			byte[] result = null;
			try {
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(mUpdateURL);
				HttpResponse httpResponse = httpClient.execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					inputStream = httpResponse.getEntity().getContent();
					// 先要获得文件的总长度
					long file_length = httpResponse.getEntity()
							.getContentLength();
					Log.e(TAG, "file_length" + file_length);
					int len = 0;
					byte[] data = new byte[1024];
					int total_length = 0;
					while ((len = inputStream.read(data)) != -1) {
						Log.e(TAG, "len" + len);
						total_length += len;
						int value = (int) ((total_length / (float) file_length) * 100);
						publishProgress(value);// 实现进度条的动态更新数据
						outputStream.write(data, 0, len);
					}

					result = outputStream.toByteArray();
					Log.e(TAG, "下载最新版本数据－－－－－data.length:" + result.length);
					outputStream.close();
				} else {
					Log.e(TAG, "输出网络状态码："
							+ httpResponse.getStatusLine().getStatusCode() + "");
					httpGet.abort();
				}
			} catch (Exception e) {
				// TODO: handle exception
			} finally {
				if (inputStream != null) {
					try {
						// File file = new File(mContext.getExternalCacheDir()
						// + "/");
						// 获取到更新链接的最后一个"／"之后的文件名
						File outFile = new File(sharedPreferences.getString(
								SharePrefUtil.APK_DIR, SharePrefUtil.APK_DIR)
								+ "Test.apk");
						if (!outFile.exists()) {
							try {
								outFile.createNewFile();
							} catch (Exception e2) {
								e2.printStackTrace();
							}
						}
						FileOutputStream fileOutputStream = new FileOutputStream(
								outFile);
						fileOutputStream.write(result);
						fileOutputStream.close();
						inputStream.close();
						update = result.toString();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						System.out.println("11111111111111111111");
						e.printStackTrace();
					}
				}
			}

			return update;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
			Log.d(TAG,
					sharedPreferences.getString(SharePrefUtil.APK_DIR,
							SharePrefUtil.APK_DIR)
							+ mUpdateURL.substring(mUpdateURL.lastIndexOf("/") + 1));
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("下载完成，是否立即安装？")
					.setPositiveButton("是",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									installApk(mUpdateURL.substring(mUpdateURL
											.lastIndexOf("/") + 1));
								}
							})
					.setNegativeButton("否",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			dialog.setProgress(values[0]);
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(getActivity());
			dialog.setTitle("正在更新...");
			dialog.setCancelable(false);
			dialog.setMax(100);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			// dialog.setIndeterminate(true);
			dialog.show();
			super.onPreExecute();
		}

	}

	/**
	 * 安装apk文件
	 * 
	 * @Title: installApk
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 * @author AT xpg
	 */
	private void installApk(String apkPath) {
		File apkfile = new File(sharedPreferences.getString(
				SharePrefUtil.APK_DIR, SharePrefUtil.APK_DIR) + apkPath);

		Intent install = new Intent();
		install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		install.setAction(android.content.Intent.ACTION_VIEW);
		install.setDataAndType(Uri.fromFile(apkfile),
				"application/vnd.android.package-archive");
		getActivity().startActivity(install);
		
	}
}
